package com.achao.basecommon.config;

import com.achao.basecommon.exception.MusicCommonException;
import com.achao.basecommon.utils.JwtUtil;

import com.achao.basecommon.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description：jwt 拦截token
 * @date：2023/8/8 23:40
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);
    @Autowired
    private RedisUtils redisUtils;
    private static final String userCachePath = "cache:backstagemanage:manage:";

    //拦截器 在执行指定方法之前拦截请求 做token认证
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 取出请求头中Authorization的信息，就是token内容，接下来就是各种判断
        String requestToken = request.getHeader("token");
        if(StringUtils.isEmpty(requestToken)){
            throw new MusicCommonException("token为空");
        }
        try{
            Claims claims = JwtUtil.parseJWT(requestToken);
            if(null == claims){
                logger.error("token过期");
                throw new MusicCommonException("token过期");
            }
            String username = String.valueOf(claims.get("username"));
            String redisCachePath = userCachePath + username;
            //token存在 则放行
            if(!redisUtils.hasKey(redisCachePath)){
                logger.info("缓存token过期,重新登录获取");
                throw new MusicCommonException("缓存token过期,重新登录获取");
            }
            return true;
        }catch(MalformedJwtException e){
            logger.error("token长度或者格式错误:{}",e.getMessage(),e);
            throw new MusicCommonException("缓存token过期,重新登录获取");
        }catch(SignatureException e){
            logger.error("无效的令牌:{}",e.getMessage(),e);
            throw new MusicCommonException("无效的令牌");
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
